import matplotlib.pyplot as plt
import datetime


def drawdata(opt):
    # 读取日志文件
    with open('output/data/data.txt', 'r') as file:
        lines = file.readlines()

    # 初始化时间段和当前时间段
    current_time = None
    no_helmet_duration = datetime.timedelta(seconds=0)
    target_detected_duration = datetime.timedelta(seconds=0)
    # 初始化计数器
    no_helmet_count = 0
    target_detected_count = 0
    # 定义检测到没有佩戴头盔和已检测到目标的关键词
    no_helmet_keyword = '检测到没有佩戴头盔'
    target_detected_keyword = '已检测到目标'
    end_detection_keyword = '结束检测'

    # 遍历日志中的每一行记录
    for line in lines:
        # 解析时间和记录
        parts = line.split(" - ")
        if len(parts) == 2:
            time_str, status = parts
            status = status.strip()

            # 检查状态信息是否包含关键词
            if no_helmet_keyword in status:
                no_helmet_count += 1
            elif target_detected_keyword in status:
                target_detected_count += 1
            elif status == end_detection_keyword:
                break  # 在找到"结束检测"记录时退出循环

    # 创建饼状图
    labels = ['no_helmet_time', 'find_target_time']
    sizes = [no_helmet_count, target_detected_count]
    colors = ['#ff9999', '#66b3ff']
    explode = (0.1, 0)  # 突出显示第一块（没有佩戴头盔）

    plt.pie(sizes, explode=explode, labels=labels, colors=colors, autopct='%1.1f%%', shadow=True, startangle=140)
    plt.axis('equal')  # Equal aspect ratio ensures that pie is drawn as a circle.

    # 显示饼状图
    plt.title('Helmet Detection Situation Statistics')
    plt.savefig('output/data/data.jpg')
    plt.show()
